package com.gy.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.gy.constant.RedisConstants;
import com.gy.controller.common.UserHolder;
import com.gy.properties.JwtProperties;
import com.gy.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

// 关键：删除 import javax.servlet.http.*; 替换为 jakarta
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private final StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("登录拦截器 - 处理请求前，线程ID:{}", Thread.currentThread().getId());

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 关键修改：和 CustomTokenFilter 一致，直接用 "token" 键获取
        String token = request.getHeader("token");
        log.debug("获取到的令牌:{}", token);

        if (StrUtil.isBlank(token)) {
            log.warn("请求头中未包含有效令牌");
            response.setContentType("application/json;charset=UTF-8"); // 新增：避免乱码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"msg\":\"令牌为空\"}");
            return false;
        }

        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);

        if (userMap.isEmpty()) {
            log.warn("令牌对应的用户信息不存在，令牌:{}", token);
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"msg\":\"令牌无效\"}");
            return false;
        }

        UserLoginVO userVo = BeanUtil.fillBeanWithMap(userMap, new UserLoginVO(), false);
        UserHolder.saveUser(userVo);

        stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        return true;
    }

    // 其他方法参数类型也改为 jakarta 的 HttpServletRequest/HttpServletResponse
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
